<template>
  <view class="example-page">
    <!-- 首页头部模块 -->
    <HomeHeader />
    
    <!-- 轮播图组件 -->
    <SwiperComponent :show-swiper="configVisible.swiper" />
    
    <!-- 热门服务 -->
    <RecommendView v-if="configVisible.recommend" />
    
    <!-- 名医护士团队 -->
    <ThreeLevelDirectoryExample />
    
            <!-- 医院切换按钮 -->
            <view class="hospital-switch-btn" @click="showHospitalSelector">
              <text class="switch-text">切换医院</text>
            </view>
            
            <!-- 机构切换按钮 -->
            <view class="nearshop-switch-btn" @click="toNearShop">
              <text class="switch-text">切换机构</text>
            </view>
  </view>
  
  <!-- 医院选择器 -->
  <BasicHospital 
    v-model:visible="hospitalModule.show" 
    :lazy-load="hospitalModule.lazyLoad"
    :title="currentUser?.defaultHospitalName || '请选择医院'" 
    @change="hospitalModule.onChange" 
  />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import Taro from '@tarojs/taro';
import HomeHeader from './HomeHeader.vue';
import ThreeLevelDirectoryExample from './ThreeLevelDirectoryExample.vue';
import RecommendView from './RecommendView.vue';
import SwiperComponent from './components/SwiperComponent.vue';
import BasicHospital from './components/BasicHospital.vue';
import { use_hospital_dept_bed, useNurseUser } from './services/HospitalService';
import { useAuthStore } from './services/UserService';
import { PlatformUtils, localStg } from './utils/PlatformUtils';
// import NearShop from './pages/NearShop.vue'; // 不需要导入，通过路由跳转

// 用户状态
const { nurseUser, updateUser } = useAuthStore();
const currentUser = ref(nurseUser.value);

// 配置可见性
const configVisible = ref({
  swiper: true,
  recommend: true,
  famous: true
});

// 医院相关
const { getHospitalList } = use_hospital_dept_bed();
const { editDefaultHospital } = useNurseUser();

// 医院选择模块
const hospitalModule = reactive({
  show: false,
  showHospital: () => {
    hospitalModule.show = !hospitalModule.show;
  },
  save: async ({ defaultHospital, defaultHospitalName }: any) => {
    Taro.showLoading({ title: '正在保存...' });
    
    try {
      const { error } = await editDefaultHospital({ 
        userId: currentUser.value?.id || '', 
        defaultHospital, 
        defaultHospitalName 
      });
      
      Taro.hideLoading();
      
      if (!error) {
        Taro.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 2000
        });
        
        // 更新用户信息
        if (currentUser.value) {
          currentUser.value.defaultHospital = defaultHospital;
          currentUser.value.defaultHospitalName = defaultHospitalName;
          updateUser(currentUser.value);
        }
        
        // 更新存储
        const defaultHospitalObj = PlatformUtils.getDefaultHospital();
        if (defaultHospitalObj) {
          defaultHospitalObj.id = defaultHospital;
          defaultHospitalObj.name = defaultHospitalName;
          Taro.setStorageSync('defaultHospital', JSON.stringify(defaultHospitalObj));
        }
      } else {
        Taro.showToast({
          title: '保存失败',
          icon: 'none',
          duration: 2000
        });
      }
    } catch (error) {
      Taro.hideLoading();
      Taro.showToast({
        title: '保存失败',
        icon: 'none',
        duration: 2000
      });
    }
  },
  onChange: (items: any) => {
    if (items.length === 0) return;
    const item = items[items.length - 1];
    hospitalModule.show = false;
    hospitalModule.save({ 
      defaultHospital: item.key, 
      defaultHospitalName: item.title 
    });
  },
  lazyLoad: async (pid: string) => {
    try {
      const { error, success } = await getHospitalList(pid);
      if (!error && success?.length > 0) {
        const list = success?.map((item: any) => {
          return {
            value: item,
            text: item.title,
            key: item.id
          };
        });
        return list;
      }
      return [];
    } catch (error) {
      console.error('加载医院列表失败:', error);
      return [];
    }
  }
});

/**
 * 显示医院选择器
 */
const showHospitalSelector = () => {
  hospitalModule.show = true;
};

/**
 * 初始化数据
 */
/**
 * 切换机构
 */
const toNearShop = () => {
  if (localStg.get('qudaoid')) {
    Taro.showToast({
      title: '该渠道不支持切换机构',
      icon: 'none',
      duration: 1200
    });
    return;
  }
  
  Taro.navigateTo({
    url: '/pages/nearshop/index',
    events: {
      switchNearShop(data: any) {
        // 切换机构后刷新数据
        initData();
      }
    }
  });
};

const initData = async () => {
  try {
    // 获取当前用户信息
    currentUser.value = nurseUser.value;
    
    // 如果没有用户信息，设置默认值
    if (!currentUser.value) {
      const defaultHospital = PlatformUtils.getDefaultHospital();
      currentUser.value = {
        id: 'default_user',
        name: '默认用户',
        defaultHospital: defaultHospital?.id || '',
        defaultHospitalName: defaultHospital?.name || '请选择医院',
        nurseUserAddrList: [],
        nurseUserFamilyList: []
      };
    }
  } catch (error) {
    console.error('初始化数据失败:', error);
  }
};

onMounted(() => {
  initData();
});
</script>

<style lang="scss" scoped>
.example-page {
  width: 100%;
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 100rpx;
}

.hospital-switch-btn {
  position: fixed;
  bottom: 200rpx;
  right: 30rpx;
  width: 120rpx;
  height: 80rpx;
  background: linear-gradient(135deg, #3b82f6, #8b5cf6);
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 24rpx rgba(59, 130, 246, 0.3);
  z-index: 999;
  
  .switch-text {
    color: white;
    font-size: 24rpx;
    font-weight: 600;
    text-align: center;
  }
  
  &:active {
    transform: scale(0.95);
  }
}

.nearshop-switch-btn {
  position: fixed;
  bottom: 300rpx;
  right: 30rpx;
  width: 120rpx;
  height: 80rpx;
  background: linear-gradient(135deg, #10b981, #059669);
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 24rpx rgba(16, 185, 129, 0.3);
  z-index: 999;
  
  .switch-text {
    color: white;
    font-size: 24rpx;
    font-weight: 600;
    text-align: center;
  }
  
  &:active {
    transform: scale(0.95);
  }
}

.notm {
  white-space: nowrap;
  padding: 10rpx 20rpx;
  border-bottom: 2rpx solid #f0f0f0;
  color: #999;
  
  &.active {
    color: #0667f8;
    border-bottom: 2rpx solid #0667f8;
  }
}

.content-area {
  padding: 40rpx;
  background: white;
  margin: 20rpx;
  border-radius: 16rpx;
}
</style>
